package xml;

import java.util.ArrayList;
import java.util.HashMap;

import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.Attributes;

public class RouteToIdIndexHandler extends DefaultHandler{

	private HashMap<ArrayList<Integer>, ArrayList<Integer>> _routeToIdMap;
	
	private HashMap<String,Integer> _labelToLabelIdMap;
	private ArrayList<Integer> _currentIdPath = new ArrayList<Integer>();
	private int _nodeId = 0;
	
	public RouteToIdIndexHandler(HashMap<ArrayList<Integer>, ArrayList<Integer>> routeToIdMap,HashMap<String,Integer> labelToLabelIdMap)
	{
		_routeToIdMap = routeToIdMap;
		_labelToLabelIdMap = labelToLabelIdMap;
	}
	
	public void startElement(String uri, String localName, String qName, Attributes attributes)  {
		
		//check if we have this label in storage already
		if (!_labelToLabelIdMap.containsKey(qName))
		{
			int labelId = _labelToLabelIdMap.size();
			
			_labelToLabelIdMap.put(qName, labelId);
			_currentIdPath.add(labelId);
		}
		else
		{
			_currentIdPath.add(_labelToLabelIdMap.get(qName));
		}
		
		
		ArrayList<Integer> currentIds = _routeToIdMap.get(_currentIdPath);
		
		if (currentIds == null)
		{
			currentIds = new ArrayList<Integer>();
			_routeToIdMap.put(new ArrayList<Integer>(_currentIdPath), currentIds);
		}
		
		currentIds.add(_nodeId);
		
		_nodeId++;
		
		if (_nodeId % 1000000 == 0)
		{
			System.out.println(_nodeId);
		}
		
	}
 
	public void endElement(String uri, String localName,
		String qName) throws SAXException {

		//trim the last id from the current path
		_currentIdPath.remove(_currentIdPath.size()-1);
 
	}
	
}
